package com.taotao.sso.service.impl;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.JsonUtils;
import com.taotao.manager.mapper.TbUserMapper;
import com.taotao.manager.pojo.TbUser;
import com.taotao.manager.pojo.TbUserExample;
import com.taotao.sso.jedis.JedisClient;
import com.taotao.sso.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private JedisClient jedis;
    @Value("${EXPIRE_TIME}")
    private Integer EXPIRE_TIME;
    @Override
    public TaotaoResult login(String username, String password) {
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)) {
            return TaotaoResult.build(400, "用户名或密码错误");
        }
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        String xpassword = DigestUtils.md5DigestAsHex(password.getBytes());

        criteria.andUsernameEqualTo(username);
        criteria.andPasswordEqualTo(xpassword);
        List<TbUser> list = userMapper.selectByExample(example);
        if (list == null || list.size() == 0) {
            return TaotaoResult.build(400, "用户名或密码错误");
        }
        TbUser user = list.get(0);
        user.setPassword(null);
        String token = UUID.randomUUID().toString();
        String key = "SESSION:" + token;
        jedis.set(key, JsonUtils.objectToJson(user));
        jedis.expire(key, EXPIRE_TIME);
        return TaotaoResult.ok(token);
    }

    @Override
    public TaotaoResult getUserByToken(String token) {
        String key = "SESSION:" + token;
        String json = jedis.get(key);
        if(StringUtils.isEmpty(json)){
            return TaotaoResult.build(400, "请重新登录");
        }
        TbUser user = JsonUtils.jsonToPojo(json, TbUser.class);
        jedis.expire(key, EXPIRE_TIME);
        return TaotaoResult.ok(user);
    }

    @Override
    public TaotaoResult logout(String token) {
        String key = "SESSION:" + token;
        jedis.expire(key, 0);
        return TaotaoResult.ok();
    }
}
